package network.UDP.Chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @author zxl
 * @version 1.0
 * @date 2021/10/22 13:34
 */
public class SendThread implements Runnable {

    private BufferedReader bufferedReader;
    private DatagramSocket socket;
    private int port;
    private String name;
    private DatagramPacket datagramPacket;

    public SendThread(String name,int port) {
        this.port = port;
        this.name = name;
        try {
            socket = new DatagramSocket();
            System.out.print(name+":");
            bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            try {
                String data = bufferedReader.readLine();
                if("再见".equals(data)){
                   break;
                }
                datagramPacket = new DatagramPacket(data.getBytes(),0,data.getBytes().length, InetAddress.getLocalHost(),port);
                socket.send(datagramPacket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
        System.exit(0);
    }
}
